<?php
/**
 * 搜索引擎管理页面
 * 展示和管理主流搜索引擎配置
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

global $wpdb;
$engines_table = $wpdb->prefix . 'spider_engines';

// 获取所有搜索引擎
$engines = $wpdb->get_results("SELECT * FROM {$engines_table} ORDER BY is_system DESC, engine_name ASC");

// 系统内置引擎图标
$engine_icons = [
    'baidu' => '🔍',
    'bing' => '🔷',
    'google' => '🔴',
    '360' => '🟢',
    'sogou' => '🟠',
    'custom' => '⚙️'
];

// 引擎状态颜色
$status_colors = [
    'active' => 'success',
    'inactive' => 'danger',
    'pending' => 'warning'
];

// 每日配额信息
$quota_info = [
    'baidu' => 3000,
    'bing' => 100,
    'google' => 200,
    '360' => 1000,
    'sogou' => 500
];

?>

<div class="wrap">
    <h1>
        <span class="dashicons dashicons-admin-site"></span>
        搜索引擎管理
    </h1>
    
    <?php settings_errors('wp_spider_engines'); ?>
    
    <div class="notice notice-info">
        <p>
            <strong>使用说明：</strong> 这里展示了主流搜索引擎的推送配置。
            系统内置引擎已预设好API地址和配额信息，您只需要填入相应的API密钥即可使用。
        </p>
    </div>
    
    <!-- 系统内置引擎 -->
    <div class="card">
        <h2 class="title">
            <span class="dashicons dashicons-star-filled"></span>
            系统内置搜索引擎
        </h2>
        
        <div class="engine-grid">
            <?php foreach ($engines as $engine): ?>
                <?php if ($engine->is_system): ?>
                    <div class="engine-card" data-engine-id="<?php echo esc_attr($engine->id); ?>">
                        <div class="engine-header">
                            <div class="engine-icon">
                                <?php echo esc_html($engine_icons[$engine->engine_type] ?? $engine_icons['custom']); ?>
                            </div>
                            <div class="engine-info">
                                <h3><?php echo esc_html($engine->engine_name); ?></h3>
                                <span class="engine-type-badge system">系统内置</span>
                            </div>
                        </div>
                        
                        <div class="engine-body">
                            <div class="form-group">
                                <label>API地址：</label>
                                <input type="text" 
                                       value="<?php echo esc_attr($engine->api_url); ?>" 
                                       readonly 
                                       class="code-input" 
                                       title="<?php echo esc_attr($engine->api_url); ?>">
                                <button type="button" class="copy-btn" data-copy="<?php echo esc_attr($engine->api_url); ?>">
                                    <span class="dashicons dashicons-admin-page"></span>
                                </button>
                            </div>
                            
                            <div class="form-group">
                                <label>API密钥：</label>
                                <div class="input-group">
                                    <input type="password" 
                                           id="api_key_<?php echo esc_attr($engine->id); ?>"
                                           value="<?php echo esc_attr($engine->api_key); ?>"
                                           placeholder="请输入您的API密钥"
                                           class="api-key-input">
                                    <button type="button" class="toggle-password" data-target="api_key_<?php echo esc_attr($engine->id); ?>">
                                        <span class="dashicons dashicons-visibility"></span>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label>每日配额：</label>
                                <span class="quota-info">
                                    <?php echo esc_html($engine->daily_quota); ?> 条/天
                                </span>
                            </div>
                            
                            <div class="form-group">
                                <label>今日已推送：</label>
                                <span class="today-pushed">
                                    <?php echo esc_html($engine->today_pushed ?? 0); ?> 条
                                </span>
                            </div>
                            
                            <div class="form-group">
                                <label>状态：</label>
                                <select class="engine-status" data-engine-id="<?php echo esc_attr($engine->id); ?>">
                                    <option value="active" <?php selected($engine->status, 'active'); ?>>
                                        启用
                                    </option>
                                    <option value="inactive" <?php selected($engine->status, 'inactive'); ?>>
                                        禁用
                                    </option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="engine-footer">
                            <button type="button" 
                                    class="button button-primary save-engine" 
                                    data-engine-id="<?php echo esc_attr($engine->id); ?>">
                                保存配置
                            </button>
                            
                            <button type="button" 
                                    class="button test-engine" 
                                    data-engine-id="<?php echo esc_attr($engine->id); ?>"
                                    data-engine-type="<?php echo esc_attr($engine->engine_type); ?>">
                                测试连接
                            </button>
                            
                            <?php if (!empty($engine->doc_url)): ?>
                                <a href="<?php echo esc_url($engine->doc_url); ?>" 
                                   target="_blank" 
                                   class="button button-link">
                                    查看文档
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- 自定义引擎 -->
    <div class="card">
        <h2 class="title">
            <span class="dashicons dashicons-admin-generic"></span>
            自定义搜索引擎
        </h2>
        
        <div class="add-engine-form">
            <h3>添加自定义搜索引擎</h3>
            <form id="add-custom-engine-form">
                <table class="form-table">
                    <tr>
                        <th><label for="engine_name">引擎名称</label></th>
                        <td>
                            <input type="text" id="engine_name" name="engine_name" required>
                            <p class="description">例如：Yandex、DuckDuckGo等</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="api_url">API地址</label></th>
                        <td>
                            <input type="url" id="api_url" name="api_url" required>
                            <p class="description">完整的API接口地址</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="api_key">API密钥</label></th>
                        <td>
                            <input type="text" id="api_key" name="api_key">
                            <p class="description">可选，如果API需要密钥验证</p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="push_method">请求方式</label></th>
                        <td>
                            <select id="push_method" name="push_method">
                                <option value="POST">POST</option>
                                <option value="GET">GET</option>
                                <option value="PUT">PUT</option>
                                <option value="DELETE">DELETE</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="daily_quota">每日配额</label></th>
                        <td>
                            <input type="number" id="daily_quota" name="daily_quota" min="1" max="10000" value="100">
                            <p class="description">每日最大推送数量限制</p>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <button type="submit" class="button button-primary">
                        添加搜索引擎
                    </button>
                </p>
            </form>
        </div>
        
        <?php 
        $custom_engines = array_filter($engines, function($engine) {
            return !$engine->is_system;
        });
        
        if (!empty($custom_engines)): 
        ?>
            <div class="custom-engines-list">
                <h3>已添加的自定义引擎</h3>
                <table class="widefat">
                    <thead>
                        <tr>
                            <th>引擎名称</th>
                            <th>API地址</th>
                            <th>状态</th>
                            <th>配额</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($custom_engines as $engine): ?>
                            <tr>
                                <td><?php echo esc_html($engine->engine_name); ?></td>
                                <td><code><?php echo esc_html($engine->api_url); ?></code></td>
                                <td>
                                    <span class="status-badge status-<?php echo esc_attr($engine->status); ?>">
                                        <?php echo $engine->status == 'active' ? '启用' : '禁用'; ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html($engine->daily_quota); ?> 条/天</td>
                                <td>
                                    <button type="button" 
                                            class="button button-small edit-engine" 
                                            data-engine-id="<?php echo esc_attr($engine->id); ?>">
                                        编辑
                                    </button>
                                    <button type="button" 
                                            class="button button-small button-danger delete-engine" 
                                            data-engine-id="<?php echo esc_attr($engine->id); ?>">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.engine-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.engine-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

.engine-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.engine-icon {
    font-size: 32px;
    margin-right: 15px;
}

.engine-info h3 {
    margin: 0 0 5px 0;
    font-size: 18px;
}

.engine-type-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 3px;
    font-size: 12px;
    color: #fff;
}

.engine-type-badge.system {
    background: #0073aa;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
}

.code-input {
    width: 100%;
    font-family: monospace;
    font-size: 12px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    padding: 5px;
}

.input-group {
    display: flex;
    align-items: center;
}

.input-group input {
    flex: 1;
    margin-right: 10px;
}

.quota-info {
    color: #0073aa;
    font-weight: bold;
}

.today-pushed {
    color: #d63638;
    font-weight: bold;
}

.engine-footer {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #eee;
    display: flex;
    gap: 10px;
    align-items: center;
}

.status-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 3px;
    font-size: 12px;
    color: #fff;
}

.status-badge.status-active {
    background: #00a32a;
}

.status-badge.status-inactive {
    background: #d63638;
}

.button-danger {
    color: #d63638;
    border-color: #d63638;
}

.add-engine-form {
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
    margin-top: 20px;
}

.custom-engines-list {
    margin-top: 30px;
}

.card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

.card .title {
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}
</style>

<script>
jQuery(document).ready(function($) {
    // 保存引擎配置
    $('.save-engine').on('click', function() {
        const engineId = $(this).data('engine-id');
        const apiKey = $('#api_key_' + engineId).val();
        const status = $('#engine_status_' + engineId).val();
        
        const data = {
            action: 'save_engine_config',
            engine_id: engineId,
            api_key: apiKey,
            status: status,
            nonce: wpSpiderMonitor.nonce
        };
        
        $.post(ajaxurl, data, function(response) {
            if (response.success) {
                showNotice('success', '配置保存成功');
            } else {
                showNotice('error', response.data || '保存失败');
            }
        });
    });
    
    // 测试引擎连接
    $('.test-engine').on('click', function() {
        const engineId = $(this).data('engine-id');
        const engineType = $(this).data('engine-type');
        
        const data = {
            action: 'test_engine_connection',
            engine_id: engineId,
            engine_type: engineType,
            nonce: wpSpiderMonitor.nonce
        };
        
        $.post(ajaxurl, data, function(response) {
            if (response.success) {
                showNotice('success', '连接测试成功');
            } else {
                showNotice('error', response.data || '连接测试失败');
            }
        });
    });
    
    // 切换密码显示
    $('.toggle-password').on('click', function() {
        const target = $(this).data('target');
        const input = $('#' + target);
        const icon = $(this).find('.dashicons');
        
        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
        } else {
            input.attr('type', 'password');
            icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
        }
    });
    
    // 复制API地址
    $('.copy-btn').on('click', function() {
        const text = $(this).data('copy');
        navigator.clipboard.writeText(text).then(function() {
            showNotice('success', '已复制到剪贴板');
        });
    });
    
    // 显示提示信息
    function showNotice(type, message) {
        const notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
        $('.wrap').prepend(notice);
        setTimeout(function() {
            notice.fadeOut(function() {
                notice.remove();
            });
        }, 3000);
    }
});
</script>